import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

//leetcode 47 全排列2
public class PermuteUnique {
    private boolean[] check;
    List<List<Integer>> list;
    List<Integer> path;
    public List<List<Integer>> permuteUnique(int[] nums) {
        check = new boolean[nums.length];
        list = new ArrayList<>();
        path = new ArrayList<>();
        Arrays.sort(nums);
        dfs(nums);
        return list;
    }

    private void dfs(int[] nums) {
        if (path.size() == nums.length) {
            list.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (check[i] == false && (i == 0 || (nums[i - 1] != nums[i] || check[i - 1] == true))) {
                path.add(nums[i]);
                check[i] = true;
                dfs(nums);
                path.remove(path.size() - 1);
                check[i] = false;
            }
        }
    }
}
